package top.wugy.blog.model;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.*;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import top.wugy.blog.kits.BlogKit;
import top.wugy.blog.kits.Const;
import top.wugy.blog.searcher.SearcherBean;

import java.util.Date;
import java.util.List;

/**
 * wugy on 2017/11/2 16:21
 */
public class TBlog extends Model<TBlog> implements IBean {

    public static final TBlog dao = new TBlog();

    public TBlog setId(Integer id) {
        return set("id", id);
    }

    public Integer getId() {
        return get("id");
    }

    public TBlog setTitle(String title) {
        return set("title", title);
    }

    public String getTitle() {
        return get("title");
    }

    public TBlog setContent(String content) {
        return set("content", content);
    }

    public String getContent() {
        return get("content");
    }

    public TBlog setStatus(Integer status) {
        return set("status", status);
    }

    public Integer getStatus() {
        return get("status");
    }

    public TBlog setTag(String tag) {
        return set("tag", tag);
    }

    public String getTag() {
        return get("tag");
    }

    public TBlog setPub(boolean pub) {
        return set("pub", pub);
    }

    public Boolean getPub() {
        return get("pub");
    }

    public TBlog setCreateTime(Date createTime) {
        return set("createTime", createTime);
    }

    public Date getCreateTime() {
        return getDate("createTime");
    }

    public Page<Record> blogList(boolean isLogin, int pageNum, String tag, String date) {
        List<Object> sqlParams = BlogKit.newArrayList();
        String whereSql = buildSql(isLogin, tag, date, sqlParams);
        Page<Record> paginate = Db.paginate(pageNum, Const.DEF_PAGE_SIZE, "SELECT *", "FROM "
                + Const.TABLE_BLOG + whereSql + " ORDER BY createTime DESC", sqlParams.toArray());
        paginate.getList().forEach(record -> record.set("createTime", BlogKit.date2Str(record.get("createTime"))));
        return paginate;
    }

    private String buildSql(boolean isLogin, String tag, String date, List<Object> sqlParams) {
        String sql = " WHERE status=?";
        sqlParams.add(Const.NORMAL);
        if (!isLogin) {
            sql += " AND pub=?";
            sqlParams.add(true);
        }
        if (StrKit.notBlank(tag)) {
            sql += " AND tag=?";
            sqlParams.add(tag);
        }
        if (StrKit.notBlank(date)) {
            sql += " AND createTime>=? AND createTime<=?";
            sqlParams.add(date + "-01 00:00:00");
            sqlParams.add(BlogKit.getLastDay(date).toString() + " 23:59:59");
        }
        return sql;
    }

    public Record findBlog(Integer blogId) {
        return Db.findById(Const.TABLE_BLOG, blogId);
    }

    public List<Record> tagList() {
        return Db.find("SELECT tag, count(tag) tagCount FROM " + Const.TABLE_BLOG + " WHERE status=? GROUP BY tag",
                Const.NORMAL);
    }

    public List<Record> archives() {
        String sql = "SELECT COUNT(1) blogCount, t2.blogDate FROM t_blog t1, " +
                "(SELECT DISTINCT(DATE_FORMAT(createTime, '%Y-%m')) blogDate FROM t_blog WHERE STATUS=?) t2 " +
                "WHERE DATE_FORMAT(t1.createTime, '%Y-%m')=t2.blogDate AND t1.status=? " +
                "GROUP BY t2.blogDate ORDER BY t2.blogDate DESC";
        return Db.find(sql, Const.NORMAL, Const.NORMAL);
    }

    public List<SearcherBean> findAll(boolean isLogin) {
        Cache cache = Redis.use(Const.REDIS_CACHE);
        String allBlogLists = cache.get("allBlogLists");
        if (StrKit.isBlank(allBlogLists)) {
            List<Object> sqlParams = BlogKit.newArrayList();
            String whereSql = buildSql(isLogin, null, null, sqlParams);
            List<TBlog> blogList = find("select id,title,content,tag,createTime from " + Const.TABLE_BLOG +
                    whereSql + " order by createTime desc", sqlParams.toArray());
            List<SearcherBean> searcherBeans = BlogKit.newArrayList(blogList.size());
            blogList.forEach(blog -> searcherBeans.add(new SearcherBean.Builder().setId(blog.getId())
                    .setTitle(blog.getTitle()).setTag(blog.getTag()).setContent(blog.getContent())
                    .setCreateTime(blog.getCreateTime()).build()));
            cache.set("allBlogLists", BlogKit.toJson(searcherBeans));
            return searcherBeans;
        }
        return BlogKit.jsonToList(allBlogLists, SearcherBean.class);
    }

}
